package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.AppManager;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.excitation.adapter.CompanyAdapter;
import com.lishe.lishe.lishe.module.excitation.adapter.StringAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.company.CompanyInfo;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.widget.MListDialog;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.InfoArrayObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/12/21.
 * 企业列表/切换企业的列表
 */

public class CompanyListActivity extends BaseActivity implements View.OnClickListener {
    private Button callBack;
    private Button moreButton;
    private TextView title;
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private int type = 0;//0=选择企业 ，1=切换企业
    private RelativeLayout empatyLayout;
    private ImageView empatyImage;
    private TextView empatyText;

    private CompanyAdapter adapter;
    private List<CompanyInfo> companys = new ArrayList<>();

    public static void jump(Activity activity, int type) {
        Intent intent = new Intent(activity, CompanyListActivity.class);
        intent.putExtra("type", type);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_list);
        type = getIntent().getIntExtra("type", 0);
        adapter = new CompanyAdapter(companys);
        initView();
    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        moreButton = findViewById(R.id.more_button);
        empatyLayout = findViewById(R.id.empty_layout);
        empatyImage = findViewById(R.id.empty_image);
        empatyText = findViewById(R.id.empty_text);
        title = findViewById(R.id.title_text_title);
        refreshLayout = findViewById(R.id.refreshlayout);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        if (type == 0) {
            title.setText("选择企业");
            moreButton.setVisibility(View.GONE);
        } else {
            title.setText("切换企业");
            moreButton.setVisibility(View.VISIBLE);
        }
        setLitener();
    }

    private void setLitener() {
        callBack.setOnClickListener(this);
        moreButton.setOnClickListener(this);
        adapter.setOnItemClick(new CompanyAdapter.OnItemtClick() {
            @Override
            public void onItemClick(int position, Object object) {
                Log.e("企业点击", ((CompanyInfo) object).getComName() + "--" + position);
//                if (type == 0) {//选择企业
//                    finish();
//                    doTokenLogin(((CompanyInfo) object).getComId());//更新token改绑comId
//                } else {//切换企业
                    CompanyConfirmActivity.jump(CompanyListActivity.this, ((CompanyInfo) object).getComId(), false);
                    finish();
//                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getCompanyList();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                /*if (type == 0) {
                    MainActivity0.jump(CompanyListActivity.this);
                }*/
                finish();
                break;
            case R.id.more_button:
                createDialog();
                break;
        }
    }

    List<String> list = new ArrayList<>();

    private void createDialog() {
        list.clear();
        list.add("加入其它企业");
        list.add("退出企业");
        StringAdapter adapter = new StringAdapter(list);
        final MListDialog.Builder dialog = new MListDialog.Builder(context);
        dialog.setAdapter(adapter);
        dialog.create().show();
        dialog.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("点击", list.get(position));
                dialog.dissmiss();
                if (position == 0) {//加入其它企业
                    JoinCompanyActivity.jump(CompanyListActivity.this, null);
                    finish();
                }
                if (position == 1) {//退出企业
                    SignOutCompanyActivity.jump(CompanyListActivity.this);
                    finish();
                }
            }
        });

    }

    /**
     * 获取企业列表
     */
    private void getCompanyList() {
        companys.clear();
        ExcitationPresenter.getInstance().getUserComAll(Globals.getToken(), new DataResponseListener<InfoArrayObject>() {
            @Override
            public void onSuccess(InfoArrayObject dataResponse) {

                refreshLayout.finishRefresh();
                companys.addAll(dataResponse.getInfo());
                adapter.notifyDataSetChanged();
                if (companys.size() > 0) {
                    empatyLayout.setVisibility(View.GONE);
                } else {
                    //MainActivity0.jump(CompanyListActivity.this,0);
                    empatyLayout.setVisibility(View.VISIBLE);
                    empatyText.setText("还没有企业，点击右上角加入企业！");
                    //finish();
                }
            }

            @Override
            public void onFail(String failMessage) {
                refreshLayout.finishRefresh();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh();
            }
        });
    }

    /**
     * 登陆
     */
    private void doTokenLogin(String comId) {
        String token = Globals.getToken();
        HttpUser.getUpToken(token, comId, responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            Log.e("跟新token", data);
            if (data != null) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                        String mtoken = jsonObject.optString("data");
                        String msg = jsonObject.optString("msg");
                        if (!TextUtils.isEmpty(mtoken) && !mtoken.equals("null")) {
                            SharedPreferencesUtils.saveToken(mtoken, CompanyListActivity.this);
                        }
                    }
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("企业登录失败！" + new String(responseBody));
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(type==0){
            AppManager.getAppManager().exitApp();
        }

    }
}
